<style rel="stylesheet/scss" lang="scss" scoped>
</style>

<template>
    <div>
        <div class="container">
            <el-card shadow="hover" style="padding:0">
                <el-row :gutter="20">
                    <el-col :span="4">
                        <el-card shadow="hover" style="padding:0">
                            <!-- 分类菜单树 -->
                            <category @tree-node-click="handleTreeNodeClick"></category>
                        </el-card>
                    </el-col>

                    <el-col :span="20">
                        <el-form ref="searchForm" :inline="true" :model="searchForm" size="medium" label-width="120px">
                            <el-card class="operate_container" shadow="never">
                                <div class="wrapper">

                                    <!-- 关键字模糊检索 -->
                                    <div class="searchKeyword">
                                        <el-form-item prop="keyword">
                                            <el-input placeholder="请输入检索关键字" v-model="searchForm.keyword" clearable @clear="handleResetSearch('searchForm')">
                                                <el-button slot="append" icon="el-icon-search" @click="handleSearch()"></el-button>
                                            </el-input>
                                        </el-form-item>
                                    </div>

                                    <!-- 操作按钮 -->
                                    <div>
                                        <el-button type="primary" icon="el-icon-plus" size="medium" circle @click="addOrUpdateVisible"></el-button>
                                        <el-button type="danger" icon="el-icon-delete" size="medium" circle @click="handleDelete"></el-button>
                                        <el-button type="primary" icon="el-icon-refresh" size="medium" circle @click="handleResetSearch('searchForm')"></el-button>
                                    </div>
                                </div>
                            </el-card>

                           
                        </el-form>

                        <!-- 表格 -->
                        <el-table
                            ref="table" size="small" empty-text="暂无数据"
                            element-loading-text="给我一点时间"
                            fit stripe border highlight-current-row
                            v-loading="dataListLoading"
                            :data="dataList"
                            :header-cell-style="{'padding-top': '10px', 'height': '50px', 'color': '#515A6E', 'background-color': '#f8f8f9'}"
                            @selection-change="handleSelection">
                            <el-table-column type="selection" width="55" align="center"></el-table-column>
                            <el-table-column type="index" width="55" align="center"></el-table-column>

                            <el-table-column label="属性名" prop="attrName" align="center"/>
                            <el-table-column label="可检索" prop="searchType" align="center" v-if="type == 1">
                                <template slot-scope="scope">
                                    <i style="color:#67C23A" class="el-icon-success" v-if="scope.row.searchType==1"></i>
                                    <i class="el-icon-error" v-else></i>
                                </template>
                            </el-table-column>
                            <el-table-column label="值类型" prop="valueType" align="center">
                                <template slot-scope="scope">
                                    <el-tag type="success" v-if="scope.row.valueType==0">单选</el-tag>
                                    <el-tag v-else>多选</el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column label="属性图标" prop="icon" align="center"/>
                            <el-table-column label="可选值" prop="valueSelect" align="center" width="150">
                                <template slot-scope="scope">
                                    <el-tooltip placement="top">
                                        <div slot="content">
                                            <span v-for="(i,index) in scope.row.valueSelect?scope.row.valueSelect.split(';'):''" :key="index">{{i}}<br/></span>
                                        </div>
                                        <el-tag v-if="scope.row.valueSelect">{{scope.row.valueSelect.split(";")[0]+'...'}}</el-tag>
                                    </el-tooltip>
                                </template>
                            </el-table-column>
                            <el-table-column label="值类型" prop="attrType" align="center"/>
                            <el-table-column label="启用" prop="enable" align="center">
                                <template slot-scope="scope">
                                <i style="color:#67C23A" class="el-icon-success" v-if="scope.row.enable==1"></i>
                                <i class="el-icon-error" v-else></i>
                                </template>
                            </el-table-column>
                            <el-table-column label="所属分类" prop="categoryName" align="center"></el-table-column>
                            <el-table-column label="所属分组" prop="groupName" align="center" v-if="type == 1"></el-table-column>
                            <el-table-column label="快速展示" v-if="type == 1" prop="showDesc" align="center">
                                <template slot-scope="scope">
                                    <i style="color:#67C23A" class="el-icon-success" v-if="scope.row.showDesc==1"></i>
                                    <i class="el-icon-error" v-else></i>
                                </template>
                            </el-table-column>
                            <el-table-column label="创建时间" prop="ctime" align="center" width="150"/>
                            <el-table-column label="更新时间" prop="utime" align="center" width="150"/>

                            <el-table-column label="操作" width="120px" align="center" fixed="right">
                                <template slot-scope="scope">
                                    <div class="table_action">
                                        <el-button type="primary" icon="el-icon-edit" circle size="small" @click="addOrUpdateVisible(scope.row)"></el-button>
                                        <el-button type="danger" icon="el-icon-delete" circle size="small" @click="handleDelete(scope.row)"></el-button>

                                        <!--
                                        <el-button type="text" size="small" @click="handleOpenDialog('edit', scope.row)">编辑</el-button>
                                        <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>

                                        <el-popover
                                            class="table_popover"
                                            placement="bottom"
                                            trigger="hover">
                                            <div class="table_popover_tools">
                                                <el-button type="text" size="small">编辑</el-button>
                                                <el-button type="text" size="small">删除</el-button>
                                            </div>
                                            <el-button icon="el-icon-s-tools" circle slot="reference" size="small"></el-button>
                                        </el-popover>
                                        -->

                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>

                        <!-- 分页工具栏 -->
                        <div class="pagination">
                            <el-pagination
                                    @size-change="handleSizeChange"
                                    @current-change="handleCurrentChange"
                                    :current-page="searchForm.page"
                                    :page-sizes="[10, 20, 30, 50, 100, 200]"
                                    :page-size="searchForm.limit"
                                    layout="total, sizes, prev, pager, next, jumper"
                                    :total="totalPage">
                            </el-pagination>
                        </div>
                    </el-col>
                </el-row>



                <!-- 窗口 -->
                <el-dialog
                    :title="!form.id ? '新增' : '修改'"
                    :visible.sync="visible" :close-on-click-modal="false" @close="handleDialogClose">
                    <el-form ref="form" :model="form" :rules="rules" label-width="120px">

                        <el-form-item label="所属分类" prop="cateId">
                            <category-cascader :categoryPath.sync="categoryPath"></category-cascader>
                        </el-form-item>
                        <el-form-item label="所属分组" prop="attrGroupId" v-if="type == 1">
                            <el-select ref="groupSelect" v-model="form.attrGroupId" placeholder="请选择" style="width: 80%;">
                            <el-option
                                v-for="item in attrGroups"
                                :key="item.id"
                                :label="item.attrGroupName"
                                :value="item.id"
                            ></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="属性名称" prop="attrName">
                            <el-input v-model="form.attrName" placeholder="属性名称" style="width: 80%;"></el-input>
                        </el-form-item>
                        <el-form-item label="属性图标" prop="icon">
                            <el-input v-model="form.icon" placeholder="属性图标" style="width: 80%;"></el-input>
                        </el-form-item>
                        <el-form-item label="属性类型" prop="attrType">
                            <el-select v-model="form.attrType" placeholder="请选择" style="width: 80%;">
                                <el-option label="规格参数" :value="1"></el-option>
                                <el-option label="销售属性" :value="0"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="值类型" prop="valueType">
                            <el-switch
                                v-model="form.valueType"
                                active-text="允许多个值"
                                inactive-text="只能单个值"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                :inactive-value="0"
                                :active-value="1">
                            </el-switch>
                        </el-form-item>
                        <el-form-item label="可选值" prop="valueSelect">
                            <el-select v-model="form.valueSelect" multiple filterable allow-create placeholder="请输入内容" style="width: 80%;"></el-select>
                        </el-form-item>

                        <el-form-item label="可检索" prop="searchType" v-if="type == 1">
                            <el-switch
                                v-model="form.searchType"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                :active-value="1"
                                :inactive-value="0"
                            ></el-switch>
                        </el-form-item>
                        <el-form-item label="快速展示" prop="showDesc" v-if="type == 1">
                            <el-switch
                                v-model="form.showDesc"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                :active-value="1"
                                :inactive-value="0"
                            ></el-switch>
                        </el-form-item>
                        <el-form-item label="启用状态" prop="enable">
                            <el-switch
                                v-model="form.enable"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                :active-value="1"
                                :inactive-value="0"
                            ></el-switch>
                        </el-form-item>
                        
                    </el-form>

                    <div slot="footer" class="dialog-footer">
                        <el-button @click="visible = false">取 消</el-button>
                        <el-button @click="handleSubmit('form')" type="primary" :loading="submitLoading">提 交</el-button>
                    </div>
                </el-dialog>
            </el-card>
        </div>
    </div>
</template>

<script>
import { save, deleted, updated, info, list, page, selectMyPage, queryAttrPage } from "@/api/product/pmsattr"
import Category from '@/views/product/components/category'
import CategoryCascader from '@/views/product/components/category-cascader'

export default {
    components: {Category, CategoryCascader},
    props: {
        type: {
            type: Number,
            default: 1
        }
    },
    data() {
        return {
            visible: false,
            searchVisible: false,
            submitLoading: false,

            dataList: [],
            totalPage: 0,
            dataListLoading: true,
            selectionRows: [],

            searchForm: {
                page: 1,
                limit: 10,
                sortColumns: null,
                sortType: null,
                keyword: null,
                cateId: 0
            },
            form: {
                id: null,
                cateId: null,
                attrGroupId: "",
                attrName: null,
                searchType: null,
                valueType: 0,
                icon: null,
                valueSelect: null,
                attrType: 1,
                enable: 1,
                showDesc: null,
                ctime: null,
                utime: null
            },
            rules: {
                cateId: [
                    { required: true, message: '所属分类不能为空', trigger: 'blur' }
                ],
                attrName: [
                    { required: true, message: '属性名不能为空', trigger: 'blur' }
                ],
                searchType: [
                    { required: true, message: '是否需要检索[0-不需要，1-需要]不能为空', trigger: 'blur' }
                ],
                valueType: [
                    { required: true, message: '值类型[0-为单个值，1-可以选择多个值]不能为空', trigger: 'blur' }
                ],
                icon: [
                    { required: true, message: '属性图标不能为空', trigger: 'blur' }
                ],
                valueSelect: [
                    { required: true, message: '可选值列表[用逗号分隔]不能为空', trigger: 'blur' }
                ],
                attrType: [
                    { required: true, message: '属性类型[0-基本属性，1-销售属性]不能为空', trigger: 'blur' }
                ]
            },

            categoryPath: [],
            attrGroups: [],
        }
    },
    mounted() {
    	this.$nextTick(function () {
	        this.getDataList()
    	})
    },
    watch: {
        categoryPath(path) {
            //监听到路径变化需要查出这个三级分类的分组信息
            this.attrGroups = [];
            this.form.attrGroupId = "";
            this.form.categoryId = path[path.length - 1];

            if (path && path.length == 3) {
                this.$http({
                    url: `/product/pmsattrgroup/list/${path[path.length - 1]}`,
                    method: "get"
                }).then(res => {
                    if (res && res.code === 200) {
                        this.attrGroups = res.data;
                    } else {
                        this.$notify({ title: '错误', message: res.msg, type: 'error' });
                    }
                });
            } else if (path.length == 0) {
                this.form.categoryId = "";
            } else {
                this.$notify({ title: '错误', message: '请选择正确的分类', type: 'error' });
                this.form.categoryId = "";
            }
        }
    },
    methods: {
        handleSelection(selection) { // 多选
            this.selectionRows = selection
        },
        handleSizeChange(val) { // 每页数量
            this.searchForm.limit = val
            this.getDataList()
        },
        handleCurrentChange(val) { // 页码
            this.searchForm.page = val
            this.getDataList()
        },
        handleResetSearch(name) { // 重置搜索表单
            this.handleReset(name)
            this.getDataList()
        },
        handleReset(name) { // 重置表单
            const refs = this.$refs
            refs[name].resetFields()
        },
        handleSearch() { // 单条件搜索
            this.getDataList()
        },
        handleDialogClose() { //表单窗口关闭
            this.handleReset('form')
        },

		/**
         * 打开表单窗口
         */
		addOrUpdateVisible(row) {
            this.visible = true
            this.$nextTick(() => {
                this.form.attrType = this.type
                if (row.id) {
                    this.getInfo(row.id).then(res => {
                        console.log(res.data);
                        this.form = Object.assign({}, res.data)
                        this.form.valueSelect = res.data.valueSelect.split(";");
                        this.categoryPath = this.form.categoryPath
                        this.$nextTick(() => {
                            this.form.attrGroupId = res.data.attrGroupId;
                        });
                    })
                } else {
                    this.form.id = null
                }
            });
        },

		/**
         * 提交表单
         */
        handleSubmit(name) {
            // 设置分类ID
            if(this.categoryPath.length > 0) {
                this.form.cateId = this.categoryPath[this.categoryPath.length-1]
            }

        	const refs = this.$refs
            refs[name].validate((valid) => {
                if (valid) {
                    this.submitLoading = true

                    this.form.valueSelect = this.form.valueSelect.join(";")

                    if (!this.form.id) {
                        save(this.form).then(res => {
                            if (this.ResultMessage(res)) {
                                this.submitLoading = false
                                this.visible = false
                                this.handleReset('form')
                                this.getDataList()
                            } else {
                                this.submitLoading = false
                            }
                        }).catch(error => {
                            this.submitLoading = false
                            this.$notify({ title: '错误', message: error, type: 'error' });
                        })
                    } else if (this.form.id) {
                        updated(this.form).then(res => {
                            if (this.ResultMessage(res)) {
                                this.submitLoading = false
                                this.visible = false
                                this.handleReset('form')
                                this.getDataList()
                            } else {
                                this.submitLoading = false
                            }
                        }).catch(error => {
                            this.submitLoading = false
                            this.$notify({ title: '错误', message: error, type: 'error' });
                        })
                    } else {
                        console.log('未知操作');
                    }
                }
            })
        },
		
		/**
         * 删除
         */
        handleDelete(row) { 
            let ids = []
            if (row.id != undefined) {
                ids.push(row.id)
            }
            if(this.selectionRows) {
                this.selectionRows.filter((item, index) => {
                    ids.push(item.id)
                })
            }
            if (ids.length <= 0) {
                this.$notify({ title: '提示', message: '请选择需要删除的记录！', type: 'info' });
            } else {    
                this.$confirm('确定要删除？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
                    deleted(ids).then(res => {
                        if (this.ResultMessage(res)) {
                            this.getDataList()
                        } 
                    }).catch(error => {
                        this.$notify({ title: '错误', message: error, type: 'error' });
                    })
                }).catch(() => {})
            }
        },

		/**
         * 详细信息
         */
        getInfo(id) {
            if (id !== undefined) {
                return info(id).then(res => {
                    if (this.ResultMessage(res, false)) {
                        return res
                    } else {
                        this.$notify({ title: '错误', message: error, type: 'error' });
                    }
                }).catch(error => {
                    this.$notify({ title: '错误', message: error, type: 'error' });
                })
            }
        },
		
        /**
         * 数据列表
         */
        getDataList() {
            let type = this.type == 0 ? "sale" : "base";
            queryAttrPage(type, this.searchForm).then(res => {
                if (this.ResultMessage(res, false)) {
                    this.dataList = res.data.records
                    this.totalPage = res.data.total
                    this.dataListLoading = false
                } else {
                    this.dataListLoading = false
                }
            }).catch(error => {
                this.dataListLoading = false
                this.$notify({ title: '错误', message: error, type: 'error' });
            })
        },

        //感知树节点被点击
        handleTreeNodeClick(data, node, component) {
            if (node.level == 3) {
                this.searchForm.cateId = data.id;
                this.getDataList(); //重新查询
            }
        }
    }
}
</script>